<template>
  <div class="container">
    <div class="userList">
      <div class="list">
        <div class="item" v-for="(item, index) in data.userList" :key="index">
          <div class="close" @click="deleteUser(item)">
            <i class="iconfont icon-close"></i>
          </div>
          <dl>
            <dt class="avatar">
              <div
                class="box"
                :class="item.sex > 0 ? 'female' : 'male'"
                @click="viewProfile(item)"
              ></div>
            </dt>
            <dd class="info">
              <h2 class="name" @click="viewProfile(item)">
                {{ item.username }}
              </h2>
              <div class="age">年龄：{{ item.age }}</div>
              <div class="date">更新时间：{{ item.lastUpdate }}</div>
            </dd>
            <dd class="buttons">
              <div class="button left" @click="showContact(item)">
                <i class="iconfont icon-phone"></i>
                <div class="text">联系</div>
              </div>
              <div class="button right" @click="bloodPreasure(item)">
                <i class="iconfont icon-pulse"></i>
                <div class="text">查看</div>
              </div>
            </dd>
          </dl>
        </div>
      </div>
    </div>
    <div class="page" v-if="!route.query.search && data.pagination.total > 0">
      <button
        class="page-btn"
        @click="goToPage(data.pagination.currentPage - 1)"
        :disabled="data.pagination.currentPage <= 1"
      >
        上一页
      </button>

      <span class="page-info">
        {{ data.pagination.currentPage }}/{{ totalPages }}
      </span>

      <button
        class="page-btn"
        @click="goToPage(data.pagination.currentPage + 1)"
        :disabled="data.pagination.currentPage >= totalPages"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script setup>
import { vConfirm } from "@/plugins/vConfirm";
import { vToast } from "@/plugins/vToast";
import { ref, reactive, onMounted, watch, computed } from "vue";
import { userList, userSearch, userDelete } from "@/api";
import router from "@/route";
import { useRoute } from "vue-router";
const route = useRoute();
const data = reactive({
  userList: [],
  pageSize: 12,
  currentPage: 1,
  pagination: {
    total: 0,
    currentPage: 1,
    pageSize: 12,
  },
}); // 计算总页数
const totalPages = computed(() => {
  return Math.ceil(data.pagination.total / data.pagination.pageSize);
});

const getUserList = () => {
  let params = {
    pageSize: data.pageSize,
    currentPage: data.currentPage,
  };

  userList(params).then((res) => {
    if (res.code == 200) {
      data.userList = res.data.users;
      // 更新分页信息
      data.pagination = {
        total: parseInt(res.data.pagination.total),
        currentPage: parseInt(res.data.pagination.currentPage),
        pageSize: parseInt(res.data.pagination.pageSize),
      };
    }
  });
};
// 跳转到指定页码
const goToPage = (page) => {
  if (page < 1 || page > totalPages.value) return;
  
  data.currentPage = page;
  getUserList();
  
  // 平滑滚动到顶部
  const container = document.querySelector('.container');
  if (container) {
    container.scrollTo({ top: 0, behavior: 'smooth' });
  }
};
const getUserSearch = (keyword) => {
  data.userList = [];
  let parmas = {
    keyword: keyword,
  };
  userSearch(parmas).then((res) => {
    if (res.code == 200) {
      data.userList = res.data.users;
    }
  });
};
const showContact = (item) => {
  vConfirm({
    title: item.username,
    message: `手机号码：${item.mobile}`,
  }).catch((res) => {});
};
const viewProfile = (item) => {
  router.push({
    path: "/viewProfile",
    query: { id: item.id }, // 传递具体id值
  });
};
const bloodPreasure = (item) => {
  router.push({
    path: "/bloodPreasure",
    query: { id: item.id }, // 传递具体id值
  });
};
const search = (keyword) => {
  console.log("执行搜索:", keyword);
  if (keyword) {
    data.currentPage = 1;
    getUserSearch(keyword);
  }
};
const deleteUser = (item) => {
  vConfirm({
    message: `确定删除用户"${item.username}"吗?`,
  }).then(() => {
    userDelete({ id: item.id }).then((res) => {
      if (res.code == 200) {
        vToast({ message: "用户删除成功！" }).then(() => {
          // 删除后重新获取数据
          if (route.query.search) {
            getUserSearch(route.query.search);
          } else {
            // 特殊处理：删除后如果当前页没有数据且不是第一页，则自动返回上一页
            if (data.userList.length === 1 && data.pagination.currentPage > 1) {
              goToPage(data.pagination.currentPage - 1);
            } else {
              getUserList();
            }
          }
        });
      }
    });
  }).catch(() => {});
};
watch(
  () => route.query.search,
  (newVal) => {
    if (newVal) {
      search(newVal);
    }
  },
  { immediate: true } // 首次加载也执行
);
onMounted(() => {
  if (!route.query.search) {
    getUserList();
  }
});
watch(
  () => route.query.search,
  (newVal) => {
    if (newVal) {
      data.currentPage = 1;
      getUserSearch(newVal);
    } else {
      data.currentPage = 1;
      getUserList();
    }
  },
  { immediate: true }
);
</script>

<style lang="less" scoped>
.searchbox {
  overflow: hidden;
  padding: 20px 20px;
  margin-bottom: 20px;
  background: #f9f9f9;
  border-radius: 3px;
}

.lines {
  overflow: hidden;
  line-height: 40px;
  float: left;
  margin-right: 30px;

  span {
    float: left;
  }

  .xingm {
    line-height: 40px;
    float: left;
    font-size: 17px;
  }
}

.container {
  flex-grow: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 1px;
  position: relative;
  padding-right: 10px;
}

.userList {
  padding-top: 10px;
  .list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
    gap: 20px;
  }
}

.item {
  box-shadow: rgba(9, 30, 66, 0.14) 0px 4px 8px -2px,
    rgba(9, 30, 66, 0.04) 0px 0px 0px 1px;
  border-radius: 4px;
  background: var(--bs-bg-color);
  transition: all 0.3s;
  background: linear-gradient(45deg, rgba(180, 209, 243, 0.7), transparent);
  backdrop-filter: blur(6px);
  border: solid 1px #b4d1f3;
  position: relative;
  .close {
    position: absolute;
    right: 0;
    top: 0;
    width: 38px;
    height: 38px;
    transform: translateX(50%) translateY(-50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    .iconfont {
      font-size: 24px;
      color: var(--bs-theme-color);
      transition: all 0.3s;
    }
    &:hover {
      .iconfont {
        color: #ff7f00;
        transform: rotate(90deg) scale(1.1);
      }
    }
  }

  .avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 0 20px 0;
    .box {
      .iconfont {
        font-size: 56px;
      }
      cursor: pointer;
      background: var(--bs-nav-link-color);
      color: var(--bs-bg-color);
      width: 88px;
      height: 88px;
      display: flex;
      justify-content: center;
      align-content: center;
      border-radius: 50%;
      background: url("@/assets/images/female.jpg") center no-repeat;
      background-size: 100% 100%;
      transition: all 0.3s;
      &.male {
        background-image: url("@/assets/images/male.jpg");
      }
    }
  }
  &:hover {
    backdrop-filter: none;
    .avatar {
      .box {
        background-color: var(--bs-theme-color);
        transform: scale(1.2);
      }
    }
  }
  .info {
    text-align: center;
  }

  h2.name {
    cursor: pointer;
    font-size: 25px;
    font-weight: normal;
    text-align: center;
    font-weight: bold;
    color: var(--bs-theme-color);
    margin-top: 10px;

    // color: var(--bs-theme-color);
    text-transform: uppercase;
    padding: 10px 0;
  }

  .date {
    font-size: 14px;
    color: var(--bs-nav-link-color);
    padding: 10px 0;
  }

  .buttons {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 10px;
    padding-bottom: 20px;
    .button {
      flex-grow: 1;
      display: flex;
      justify-content: center;
      height: 34px;
      line-height: 34px;
      gap: 8px;
      cursor: pointer;
      transition: all 0.3s;
      border-radius: 4px;
      position: relative;
      &::before {
        // content: "";
        display: block;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-image: radial-gradient(transparent 1px, #fff 1px);
        background-size: 4px 4px;
        backdrop-filter: saturate(50%) blur(4px);
        opacity: 0.2;
      }

      &.left {
        border-right: var(--bs-border-color) 1px solid;
        background: #ff7f00;
        color: white;
      }

      &.right {
        background: var(--bs-theme-color);
        color: white;
      }

      &:hover {
        opacity: 0.6;
      }
    }
  }
}
.page {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  padding: 20px 0;
  
  .page-btn {
    padding: 8px 20px;
    margin: 0 10px;
    border: 1px solid var(--bs-border-color);
    border-radius: 4px;
    background-color: white;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover:not(:disabled) {
      background-color: var(--bs-theme-color);
      color: white;
      border-color: var(--bs-theme-color);
    }
    
    &:disabled {
      cursor: not-allowed;
      opacity: 0.5;
    }
  }
  
  .page-info {
    padding: 5px 15px;
    background: rgba(180, 209, 243, 0.2);
    border-radius: 4px;
    min-width: 80px;
    text-align: center;
    font-weight: bold;
  }
}
</style>